from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class helpers(object):
    # some static helpers
    def getIpFromRequest(request):        
        return request.remote_addr
    
    def getAgentFromRequest(request):        
        return request.headers['User-Agent']
    
    getIpFromRequest = staticmethod(getIpFromRequest)
    getAgentFromRequest = staticmethod(getAgentFromRequest)

class hello(webapp.RequestHandler):
    # A simple echo service.    
    def get(self):
        self.response.headers['Content-Type'] = 'application/plain'
        self.response.out.write('Hello World!')
        
class ip(webapp.RequestHandler):
    # Returns the requesters IP in json format.
    # TODO: introduce a format parameter; plain, json, xml
    def get(self):
        self.response.headers['Content-Type'] = 'application/json'
        reqIp = helpers.getIpFromRequest(self.request)
        
        self.response.out.write("{\"ip\":\"%s\"}" % reqIp)
        
class useragent(webapp.RequestHandler):
    # Returns the user agent string in json format.
    # TODO: introduce a format parameter; plain, json, xml
    def get(self):
        self.response.headers['Content-Type'] = 'application/json'
        reqAgent = helpers.getAgentFromRequest(self.request)
                
        self.response.out.write("{\"user\": \"%s\"}" % reqAgent)     
        
class info(webapp.RequestHandler):
    # Return both the ip and user agent   
    def get(self):
        self.response.headers['Content-Type'] = 'application/json'
        reqAgent = helpers.getAgentFromRequest(self.request)
        reqIp = helpers.getIpFromRequest(self.request)
        
        self.response.out.write("{\"ip\":\"%s\",\"user\":\"%s\"}" % (reqIp, reqAgent))
        
application = webapp.WSGIApplication(
                                     [('/', info),
                                      ('/hello', hello),
                                      ('/useragent', useragent),
                                      ('/ip', ip),
                                      ('/info', info)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
